package com.hoshiicloud.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateUtil extends DateUtils {


    public final static String DATE_FORMAT = "yyyy-MM-dd";

    public final static String DATEPICKER_FORMAT = "MM/dd/yyyy";

    public final static String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";


    public static Date getDate(String pattern) {
        if (pattern == null) {
            return null;
        }
        SimpleDateFormat dateFormat = null;
        if (pattern.indexOf("/") != -1) {
            dateFormat = new SimpleDateFormat(DATEPICKER_FORMAT);
        } else if (pattern.indexOf(":") != -1) {
            dateFormat = new SimpleDateFormat(TIME_FORMAT);
        } else {
            dateFormat = new SimpleDateFormat(DATE_FORMAT);
        }
        try {
            return dateFormat.parse(pattern);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 根据格式得到格式化后的日期
     *
     * @param date    要格式化的日期
     * @param pattern 日期格式，如yyyy-MM-dd
     * @return String 返回格式化后的日期，格式由参数<code>format</code>
     * 定义，如yyyy-MM-dd，如2006-02-15
     */

    public static String formateDate(Date date, String pattern) {
        if (null == date) {
            return StringUtils.EMPTY;
        }
        SimpleDateFormat dtFormatdB = null;
        try {
            dtFormatdB = new SimpleDateFormat(pattern);
            return dtFormatdB.format(date);
        } catch (Exception e) {
            dtFormatdB = new SimpleDateFormat(DATE_FORMAT);
            try {
                return dtFormatdB.format(date);
            } catch (Exception ex) {
            }
        }
        return null;
    }


    /**
     * 通过时间秒毫秒数判断两个时间的间隔
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
        return days;
    }

    /**
     * 获取两个时间相隔的分钟数
     * @param date1 时间1
     * @param date2 时间2
     * @return Long
     */
    public static Long differentMinsByMillisecond(LocalDateTime date1, LocalDateTime date2) {
        Long mins = (date2.toInstant(ZoneOffset.of("+8")).toEpochMilli() - date1.toInstant(ZoneOffset.of("+8")).toEpochMilli()) / (1000*60);
        return mins;
    }

    public static void main(String[] args) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime begin = LocalDateTime.parse("2019-09-03 19:00:37",df);
        LocalDateTime end = LocalDateTime.now();
        System.out.println(differentMinsByMillisecond(begin,end));
    }

}
